package com.qf.common.security.interceptor;

import com.qf.common.core.utils.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 权限拦截器 -> 手动获取用户信息，放入SecurityContext中，使得权限注解生效
 */
@Slf4j
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取当前用户信息
        UserDetails userDetails = UserInfo.getUser();
        log.debug("[security-interceptor] - 权限设置拦截器，获取用户信息放入Security上下中 - {}", userDetails);
        Optional.ofNullable(userDetails)
                .ifPresent(userDetail -> {
                    //将用户信息转换成Authentication对象（用户身份）
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                            = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
                    //放入Security上下文容器中
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                });

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        SecurityContextHolder.getContext().setAuthentication(null);
        super.postHandle(request, response, handler, modelAndView);
    }
}
